import React, {useEffect, useMemo, useState} from 'react'
import {
	Form,
	Row,
	Col,
	Input,
	InputNumber,
	Select,
	DatePicker,
	Cascader,
	TreeSelect,
} from 'antd'
import zhCN from 'antd/es/date-picker/locale/zh_CN'
import moment from 'moment'
import 'moment/locale/zh-cn'
// import { PageType } from '../constant';
import Styles from './index.less'
import {getSubjectCompany} from '@/service/merchantCenter/clue'
import {getAllCitysPermission, getCompany} from '@/service/common'
import {modelSeriesFun, translateDataToTree} from '@/utils/common'
import {getDictsByKeys} from '@/service/common/dict'
import {getCarTypeList} from '@/service/carMessage/list'
import {
	createNoc,
	getFirstChannelType,
	getSecondChannelType,
} from '@/service/merchantCenter/channelRule'
import {FormSelect} from '@/components/SearchForm/SearchFormItem'

moment.locale('zh-cn')

interface BasicsType {
	pageType: string
	basicsForm: any
	detailRecord: Record<string, string>
	callback: (e: any) => void
	// eslint-disable-next-line react/require-default-props
	user?: any
	routerQuery: any
}

const cityNames = {
	label: 'name',
	value: 'id',
	children: 'cityInfoList',
}

// 申请部门与项目申请人
const deptAddUserNames = {
	label: 'name',
	value: 'id',
	key: 'id',
}

const {Option} = Select

function StableLeasing(props: any) {
	const {value, onChange, disabled} = props
	return (
		<div className={Styles.inputBox}>
			<div className={Styles.input}>
				<InputNumber
					value={value}
					onChange={onChange}
					placeholder="请输入"
					disabled={disabled}
				/>
			</div>
			<div className={Styles.text}>天</div>
		</div>
	)
}

function LeaseTerm(props: any) {
	const {value, onChange, disabled} = props
	return (
		<div className={Styles.inputBox}>
			<div className={Styles.input}>
				<InputNumber
					placeholder="请输入"
					value={value}
					onChange={onChange}
					disabled={disabled}
				/>
			</div>
			<div className={Styles.text}>天内无订单给奖励</div>
		</div>
	)
}

export function Basics({
	pageType,
	basicsForm,
	detailRecord,
	user,
	callback,
	routerQuery,
}: BasicsType) {
	const disabled = useMemo(
		() => pageType === 'detail' || pageType === 'audit',
		[pageType],
	)
	const spanLen = routerQuery?.type === '1' ? 12 : 8
	const [subjectList, setSubjectList] = useState([])
	const [orgList, setOrgList] = useState([])
	const [citysList, setCitysList] = useState<any[]>([])
	// eslint-disable-next-line camelcase
	const [Settlement_Cycle, setSettlement_Cycle] = useState([])
	// eslint-disable-next-line camelcase
	const [order_rent_type, setOrder_rent_type] = useState([])
	// eslint-disable-next-line camelcase
	const [filing_method, setFiling_method] = useState([])
	// eslint-disable-next-line camelcase
	const [step_calculation, setStep_calculation] = useState([])

	const [channelTypeOneType, setChannelTypeOneType] = useState([])
	const [channelTypeTwoType, setChannelTypeTwoType] = useState([])
	const [firstLevelType, setFirstLevelType] = useState('')

	const [mainBodyId, setMainBody] = useState() // 主体ID
	const [orgId, setOrgId] = useState() // 公司ID
	const [startDate, setStartDate] = useState<any>()
	const [endDate, setEndDate] = useState<any>()

	// 根据主体id查询公司
	useEffect(() => {
		if (mainBodyId) {
			getCompany({merchantId: mainBodyId}).then((res: any) => {
				if (res?.success) {
					const data = res?.data
					res?.data?.forEach(
						(
							item: {disabled: boolean; type: any},
							index: number,
						) => {
							if (item.type !== 0) {
								data[index].disabled = true
							}
						},
					)
					const list = translateDataToTree(data)
					setOrgList(list as any)
				}
			})
		}
	}, [mainBodyId])
	// 根据公司id查询城市
	useEffect(() => {
		if (orgId) {
			getAllCitysPermission({
				permission: user?.permissionID,
				orgId,
			}).then((res: any) => {
				if (res?.data) {
					setCitysList(() => res.data)
				}
			})
		}
	}, [orgId])

	const getChannelTypeOneType = () => {
		getFirstChannelType().then((res: any) => {
			if (res?.data?.length) {
				setChannelTypeOneType(res.data)
			}
		})
	}

	const firstLevelTypeChange = (type: any) => {
		setFirstLevelType(type)
		// setFirstLevel(false)
		basicsForm.setFieldValue('channelTypeTwo', undefined)
		// setChannelTypeTwoType('')
		getSecondChannelType({type}).then((res: any) => {
			if (res.success) {
				setChannelTypeTwoType(res.data)
			}
		})
	}

	// const getChannelTypeTwoType = () => {
	//   getSecondChannelType().then((res:any)=>{
	//     if(res?.data?.length){
	//       setChannelTypeTwoType(res.data)
	//     }
	//   })
	// }

	const getSubjectFun = () => {
		getSubjectCompany().then((res: any) => {
			if (res.data) {
				setSubjectList(res.data.data)
			}
		})
	}

	const getKeyList = () => {
		getDictsByKeys({
			dictKeys: [
				'Settlement_Cycle',
				'order_rent_type',
				'filing_method',
				'step_calculation',
			],
		}).then((res: any) => {
			if (res?.data?.length) {
				res.data.forEach((item: any) => {
					if (item.name === 'Settlement_Cycle') {
						setSettlement_Cycle(item.listDicts)
					}
					if (item.name === 'order_rent_type') {
						setOrder_rent_type(item.listDicts)
					}
					if (item.name === 'filing_method') {
						setFiling_method(item.listDicts)
					}
					if (item.name === 'step_calculation') {
						setStep_calculation(item.listDicts)
					}
				})
			}
		})
	}
	const [BrandList, setBrandList] = useState([])

	const getBrandtype = () => {
		getCarTypeList().then((res: any) => {
			if (res?.data?.length) {
				setBrandList(modelSeriesFun(res.data))
			}
		})
	}

	useEffect(() => {
		getSubjectFun()
		getKeyList()
		getBrandtype()
		getChannelTypeOneType()
	}, [])

	// const onCitysChange = (value: any, selectedOptions: any) => {
	// 	if (value) {
	// 		basicsForm.setFieldsValue({
	// 			cityName: selectedOptions[selectedOptions.length - 1].name,
	// 			cityId: selectedOptions[selectedOptions.length - 1].id,
	// 		})
	// 	}
	// }
	const onCitysChange = (value: any, selectedOptions: any) => {
		if (value) {
			basicsForm.setFieldsValue({
				cityName: selectedOptions[selectedOptions.length - 1].name,
			})
		}
	}

	const TreeSelectChange = (value: any, e: any) => {
		setOrgId(value)
		basicsForm.setFieldsValue({orgName: e[0], cityId: undefined})
	}

	const subjectOnchange = (value: any, e: any) => {
		setMainBody(value)
		basicsForm.setFieldsValue({
			subjectName: e.children,
			orgId: undefined,
			cityId: undefined,
		})
	}

	const [channelNo, setChannelNo] = useState('')
	const getChannelNo = () => {
		createNoc().then((res: any) => {
			if (res.data) {
				setChannelNo(res.data)
			}
		})
	}

	useEffect(() => {
		getChannelNo()
	}, [])
	const initialValues = useMemo(() => {
		let value: any = {}
		if (pageType) {
			value = detailRecord
			setMainBody(value?.subject)
			setOrgId(value?.orgId)
			setStartDate(moment(value?.startDate))
			setEndDate(moment(value?.endDate))
			if (value.startDate) {
				value.startDate = moment(value.startDate)
			}
			if (value.endDate) {
				value.endDate = moment(value.endDate)
			}
			if (value.channelTypeTwo) {
				value.channelTypeTwo = value.channelTypeTwo.toString()
			}
			if (value.channelTypeOne) {
				getSecondChannelType({type: value.channelTypeOne}).then(
					(res: any) => {
						if (res.success) {
							setChannelTypeTwoType(res.data)
						}
					},
				)
			}
			if (value?.brand) {
				if (typeof value?.brand === 'string') {
					const value1 = value?.brand?.split(',')
					value.brand = value1.map((item: any) => Number(item))
				} else {
					value.brand = value?.brand.map((item: any) => Number(item))
				}
			}
			if (value?.leaseTerm) {
				if (typeof value?.leaseTerm === 'string') {
					value.leaseTerm = value?.leaseTerm
						?.split(',')
						.map((item: any) => Number(item))
				} else {
					value.leaseTerm = value?.leaseTerm?.map((item: any) =>
						Number(item),
					)
				}
			}
			if (value?.orderType) {
				if (typeof value?.orderType === 'string') {
					value.orderType = value?.orderType
						?.split(',')
						.map((item: any) => Number(item))
				} else {
					value.orderType = value?.orderType?.map((item: any) =>
						Number(item),
					)
				}
			}
			// if (value.channelType) {
			// 	const channelType = value.channelType.split(',')
			// 	// eslint-disable-next-line prefer-destructuring
			// 	value.firstLevelType = channelType[0]
			// 	// eslint-disable-next-line prefer-destructuring
			// 	value.secondLevelType = channelType[1]?.toString()
			// 	delete value.channelType
			// }
		} else {
			value = {channelNo}
			if (routerQuery.type === '1') {
				setMainBody(routerQuery?.subjectId)
				setOrgId(routerQuery?.affiliatedCompanyId)
				value.subject = Number(routerQuery.subjectId)
				value.orgId = Number(routerQuery.affiliatedCompanyId)
				value.subjectName = routerQuery.subjectName
				value.orgName = routerQuery.affiliatedCompany
				value.cityId = [
					Number(routerQuery.provinceId),
					Number(routerQuery.cityId),
				]
				value.cityName = routerQuery.cityName
				value.provinceId = Number(routerQuery.provinceId)
				value.leaseTerm = [Number(routerQuery.leaseTerm)]
				value.startDate = moment(routerQuery.beginTime)
				value.endDate = moment(routerQuery.endTime)
				value.brand = [Number(routerQuery.brandId)]
				value.orderType = [Number(routerQuery.rentTypeId)]
			}
		}
		// else {
		// 	value = {ditchNo}
		// }
		setTimeout(() => basicsForm.resetFields(), 1)
		return value
	}, [detailRecord, channelNo, routerQuery])

	return (
		<div className={Styles.basics}>
			<div className={Styles.titleBox}>基础信息</div>
			<div className={Styles.formBox}>
				<Form
					layout="horizontal"
					labelCol={{flex: '180px'}}
					labelAlign="right"
					labelWrap
					autoComplete="off"
					name="PersonalInformationFom"
					form={basicsForm}
					disabled={pageType === 'detail'}
					initialValues={initialValues}>
					<Row>
						<Col span={spanLen}>
							<Form.Item
								label="编码"
								name="channelNo"
								rules={[{required: !!pageType}]}>
								<Input placeholder="自动生成" disabled />
							</Form.Item>
						</Col>

						<Col span={spanLen}>
							<Form.Item
								label="名称"
								name="name"
								rules={[{required: true}]}>
								<Input
									placeholder="请输入"
									disabled={disabled}
								/>
							</Form.Item>
						</Col>
						<Col span={spanLen} />
					</Row>
					<Row>
						<Col span={spanLen}>
							<Form.Item
								label="主体"
								name="subject"
								rules={[{required: true}]}>
								<Select
									placeholder="请选择"
									disabled={
										disabled || routerQuery.type === '1'
									}
									allowClear
									onChange={subjectOnchange}>
									{subjectList.map((item: any) => (
										<Option value={item?.id}>
											{item?.merchantName}
										</Option>
									))}
								</Select>
							</Form.Item>
						</Col>
						<Col span={spanLen}>
							<Form.Item
								label="所属公司"
								name="orgId"
								rules={[{required: true}]}>
								<TreeSelect
									showSearch
									style={{width: '100%'}}
									placeholder="请选择"
									disabled={
										disabled || routerQuery.type === '1'
									}
									fieldNames={deptAddUserNames}
									onChange={TreeSelectChange}
									treeDefaultExpandAll
									treeData={orgList}
								/>
							</Form.Item>
						</Col>
						<Col span={spanLen}>
							<Form.Item
								label="城市"
								name="cityId"
								rules={[{required: true}]}>
								<Cascader
									fieldNames={cityNames}
									options={citysList}
									placeholder="请选择"
									disabled={
										disabled || routerQuery.type === '1'
									}
									onChange={onCitysChange}
								/>
							</Form.Item>
						</Col>
					</Row>
					<Row>
						<Col span={spanLen}>
							<Form.Item
								label="AMC一级渠道类型"
								name="channelTypeOne"
								rules={[{required: true}]}>
								<Select
									disabled={disabled}
									placeholder="请选择 "
									onChange={firstLevelTypeChange}>
									{channelTypeOneType.map((item: any) => (
										<Option value={item.type}>
											{item.valueName}
										</Option>
									))}
								</Select>
							</Form.Item>
						</Col>
						<Col span={spanLen}>
							<Form.Item
								label="AMC二级渠道类型"
								name="channelTypeTwo"
								rules={[{required: true}]}>
								<Select
									placeholder="请选择 "
									disabled={
										pageType === 'edit'
											? false
											: !firstLevelType
									}
									onChange={(e: any) => {
										callback(Number(e))
									}}>
									{channelTypeTwoType.map((item: any) => (
										<Option value={item.value}>
											{item.valueName}
										</Option>
									))}
								</Select>
							</Form.Item>
						</Col>
						<Col span={spanLen}>
							<Form.Item
								label="租期"
								name="leaseTerm"
								rules={[{required: true}]}>
								<Select
									disabled={
										disabled || routerQuery.type === '1'
									}
									mode="multiple"
									placeholder="请选择"
									options={Settlement_Cycle.map(
										(item: any) => ({
											value: item.value,
											label: item.valueName,
										}),
									)}
								/>
							</Form.Item>
						</Col>
					</Row>
					<Row>
						<Col span={spanLen}>
							<Form.Item
								label="开始时间"
								name="startDate"
								rules={[{required: true}]}>
								<DatePicker
									locale={zhCN}
									allowClear={false}
									onChange={(date) => {
										setStartDate(date)
									}}
									disabledDate={(current) =>
										current && current > endDate
									}
									disabled={
										disabled || routerQuery.type === '1'
									}
								/>
							</Form.Item>
						</Col>
						<Col span={spanLen}>
							<Form.Item
								label="结束时间"
								name="endDate"
								rules={[{required: true}]}>
								<DatePicker
									allowClear={false}
									onChange={(date) => {
										setEndDate(date)
									}}
									disabledDate={(current) =>
										current && current < startDate
									}
									locale={zhCN}
									disabled={
										disabled || routerQuery.type === '1'
									}
								/>
							</Form.Item>
						</Col>
						<Col span={spanLen}>
							<FormSelect
								filterOption
								label="品牌/车型/车系"
								name="brand"
								placeholder="请选择品牌/车型/车系"
								items={BrandList}
								disabled={disabled || routerQuery.type === '1'}
								keys="id"
								title="fullName"
								rules={[{required: true}]}
								mode="multiple"
							/>
						</Col>
					</Row>
					<Row>
						<Col span={spanLen}>
							<Form.Item
								label=" 租赁类型"
								name="orderType"
								rules={[{required: true}]}>
								<Select
									mode="multiple"
									placeholder="请选择"
									disabled={
										disabled || routerQuery.type === '1'
									}
									options={order_rent_type.map(
										(item: any) => ({
											value: item?.value,
											label: item?.valueName,
										}),
									)}
								/>
							</Form.Item>
						</Col>
						<Col span={spanLen}>
							<Form.Item
								label="结算时是否在租"
								name="isRenting"
								rules={[{required: true}]}>
								<Select
									placeholder="请选择 "
									disabled={disabled}>
									<Option value={0}>否</Option>
									<Option value={1}>是</Option>
								</Select>
							</Form.Item>
						</Col>
					</Row>
					<Row>
						<Col span={spanLen}>
							<Form.Item
								label="稳定租赁满"
								name="stableLeasing"
								rules={[{required: true}]}>
								<StableLeasing disabled={disabled} />
							</Form.Item>
						</Col>
						<Col span={spanLen}>
							<Form.Item
								label="下单前"
								name="placeOrder"
								rules={[{required: true}]}>
								<LeaseTerm disabled={disabled} />
							</Form.Item>
						</Col>
					</Row>
					<Row>
						<Col span={spanLen}>
							<Form.Item
								label="阶梯奖励提档方式"
								name="proMethod"
								rules={[{required: true}]}>
								<Select
									placeholder="请选择 "
									disabled={disabled}>
									{filing_method.map((item: any) => (
										<Option value={item?.value}>
											{item?.valueName}
										</Option>
									))}
								</Select>
							</Form.Item>
						</Col>
						<Col span={spanLen}>
							<Form.Item
								label="阶梯计算"
								name="stepCalculation"
								rules={[{required: true}]}>
								<Select
									placeholder="请选择 "
									disabled={disabled}>
									{step_calculation.map((item: any) => (
										<Option value={item?.value}>
											{item?.valueName}
										</Option>
									))}
								</Select>
							</Form.Item>
						</Col>
					</Row>
					<Row>
						<Col span={24}>
							<Form.Item label="备注" name="description">
								<Input.TextArea
									disabled={disabled}
									placeholder={
										disabled ? '' : '请输入(最多200字)'
									}
									rows={6}
								/>
							</Form.Item>
						</Col>
					</Row>
					<Form.Item
						label="1"
						name="cityName"
						style={{display: 'none'}}>
						<Input />
					</Form.Item>
					<Form.Item
						label="2"
						name="orgName"
						style={{display: 'none'}}>
						<Input />
					</Form.Item>
					<Form.Item
						label="3"
						name="subjectName"
						style={{display: 'none'}}>
						<Input />
					</Form.Item>
					<Form.Item
						label="3"
						name="provinceId"
						style={{display: 'none'}}>
						<Input />
					</Form.Item>
				</Form>
			</div>
		</div>
	)
}
